package com.wenwu.controller.work;

import java.net.URLDecoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.wenwu.common.bean.RelicsArchaeologicalWithBLOBs;
import com.wenwu.common.bean.RelicsAttachment;
import com.wenwu.common.page.PageUtils;
import com.wenwu.common.page.PaginationVO;
import com.wenwu.common.utils.JsonUtils;
import com.wenwu.common.utils.Status.AttachmentFrom;
import com.wenwu.service.CommonService;
import com.wenwu.service.WorkArchaeologicalService;

/**
 * 
 * @author Yaphet
 *
 */
@Controller(value = "WorkArchaeologicalController")
@RequestMapping(value = "/mgr/archaeological")
public class WorkArchaeologicalController {

Logger log = Logger.getLogger(this.getClass());
	
	private JsonGenerator jsonGenerator;

	@Autowired
	private CommonService commonService;
	
	@Autowired
	private WorkArchaeologicalService workArchaeologicalService;
	
	/**
	 * 
	 * @return
	 */
	@RequestMapping(value = "/init")
	public String init(){
		return "warchaeological/init";
	}
	
	/**
	 * 进入新增表单页面
	 * @return
	 */
	@RequestMapping(value = "/addForm")
	public String dictionaryform(Model model,
			@RequestParam(required=false,value="archId" )Integer archId,
			@RequestParam(required=false,value="workId" )Integer workId,
			@RequestParam(required=false,value="code" )String code,
			@RequestParam(required=false,value="projectName" )String projectName) {
		log.info("进入基本信息表单页面...");
		
		try {
			if (archId != null) {
				List<RelicsAttachment> attachments;
				attachments = commonService.selectAttachmentListByKey(
						archId,AttachmentFrom.RELICS_ARCHAEOLOGICAL_01,
							AttachmentFrom.RELICS_ARCHAEOLOGICAL_02,
							AttachmentFrom.RELICS_ARCHAEOLOGICAL_03,
							AttachmentFrom.RELICS_ARCHAEOLOGICAL_04,
							AttachmentFrom.RELICS_ARCHAEOLOGICAL_05);
				model.addAttribute("attachments", attachments);
				model.addAttribute("archId",  archId);
			}else if (workId != null) {
				List<RelicsAttachment> attachments;
				attachments = commonService.selectAttachmentListByKey(
						workId, "relics_work", "arch_id",
						"work_id", AttachmentFrom.RELICS_ARCHAEOLOGICAL_01,
						AttachmentFrom.RELICS_ARCHAEOLOGICAL_02,
						AttachmentFrom.RELICS_ARCHAEOLOGICAL_03,
						AttachmentFrom.RELICS_ARCHAEOLOGICAL_04,
						AttachmentFrom.RELICS_ARCHAEOLOGICAL_05);

				model.addAttribute("attachments", attachments);
				model.addAttribute("workId",  workId);
			}
			if(code!=null)
				model.addAttribute("code",  URLDecoder.decode(code, "UTF-8"));
			if(projectName!=null)
				model.addAttribute("projectName", URLDecoder.decode(projectName, "UTF-8"));
		} catch (Exception e) {
			log.info(e.getMessage(),e);
		}
		return "warchaeological/warchaeologicalform";
	}
	
	/**
	 * 显示要修改的信息
	 * 
	 * @param response
	 * @param userId
	 * @throws Exception
	 */
	@RequestMapping(value = "/showUpdate")
	public void showUpdate(HttpServletResponse response,
			@RequestParam(required=false, value = "workId") Integer workId,
			@RequestParam(required=false, value = "archId") Integer archId){
		try {
			RelicsArchaeologicalWithBLOBs relicsArchaeological;
			if (archId != null) {
				relicsArchaeological = workArchaeologicalService.selectBySelftKey(archId);
			} else {
				relicsArchaeological = workArchaeologicalService.selectByWorktKey(workId);
			}
			jsonGenerator = JsonUtils.getJsonGenerator(response);
			jsonGenerator.writeObject(relicsArchaeological);
		} catch (Exception e) {
			log.info(e.getMessage(), e);
		}
	}
	/**
	 * 添加
	 */
	@RequestMapping(value = "/saveaddForm")
	public void addBasic(
			@RequestParam(required=false,value="workId" )Integer workId,
			RelicsArchaeologicalWithBLOBs relicsArchaeological,HttpServletResponse response) throws Exception {
		jsonGenerator = JsonUtils.getJsonGenerator(response);
		log.info("添加/修改数据：");
		try {
			jsonGenerator.writeObject(workArchaeologicalService.addObj(relicsArchaeological,workId));
		} catch (Exception e) {// 异常处理
			log.info(e.getMessage(),e);
			jsonGenerator.writeObject(e.getMessage());
		}
	}
	
	/**
	 * 删除信息
	 * 
	 * @param response
	 * @param request
	 * @param key
	 * @throws Exception
	 */
	@RequestMapping(value = "/deleteInfo")
	public void deleteInfo(HttpServletResponse response,
			HttpServletRequest request,
			@RequestParam(required = false, value = "keys") String keys)
			throws Exception {
		jsonGenerator = JsonUtils.getJsonGenerator(response);
		try {
			String result = workArchaeologicalService.deleteBykeys(keys);
			jsonGenerator.writeObject(result);
		} catch (Exception e) {
			log.info(e.getMessage(),e);
			jsonGenerator.writeObject("删除数据失败");
		}
	}
	
	/**
	 * 可移动文物登记表表单查询
	 * @return
	 */
	@RequestMapping(value = "/showList")
	public void showList(RelicsArchaeologicalWithBLOBs relicsArchaeological,Model model, HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(required = false, value = "startTimeStart") String startTimeStart,
			@RequestParam(required = false, value = "startTimeEnd") String startTimeEnd,
			@RequestParam(required = false, value = "endTimeStart") String endTimeStart,
			@RequestParam(required = false, value = "endTimeEnd") String endTimeEnd) {
		PaginationVO pageVo = PageUtils.getPaginationInfo(request);
		try {
			if(relicsArchaeological!=null && relicsArchaeological.getCode() != null){
				relicsArchaeological.setCode(relicsArchaeological.getCode().trim());
			}
			if(relicsArchaeological!=null && relicsArchaeological.getProjectName() != null){
				relicsArchaeological.setProjectName(relicsArchaeological.getProjectName().trim());
			}
			//封装时间查询条件
			StringBuffer timeSql = new StringBuffer();
			if(startTimeStart!= null && !"".equals(startTimeStart.trim())){
				timeSql.append("and begintime >= date('");
				timeSql.append(startTimeStart);
				timeSql.append("')");
			}
			if(startTimeEnd != null && !"".equals(startTimeEnd.trim())){
				timeSql.append("and begintime <= date('");
				timeSql.append(startTimeEnd);
				timeSql.append("')");
			}
			if(endTimeStart!= null && !"".equals(endTimeStart.trim())){
				timeSql.append("and endtime >= date('");
				timeSql.append(endTimeStart);
				timeSql.append("')");
			} 
			if(endTimeEnd != null && !"".equals(endTimeEnd.trim())){
				timeSql.append("and endtime <= date('");
				timeSql.append(endTimeEnd);
				timeSql.append("')");
			}
			relicsArchaeological.setTimeSQL(timeSql.toString());
			pageVo = workArchaeologicalService.selectByCondition(relicsArchaeological, pageVo);
			jsonGenerator = JsonUtils.getJsonGenerator(response);
			jsonGenerator.writeObject(pageVo);// 将PaginationVO对象以json格式写回页面
		} catch (Exception e) {// 异常处理
			log.info(e.getMessage(),e);
			model.addAttribute("errorMsg", "系统异常，请稍后重试!");
		}
	}
}
